package com.tunnel.home.rest;

import org.axe.annotation.ioc.Autowired;
import org.axe.annotation.ioc.Controller;
import org.axe.annotation.mvc.FilterFuckOff;
import org.axe.annotation.mvc.Request;
import org.axe.annotation.mvc.RequestParam;
import org.axe.bean.mvc.Param;
import org.axe.constant.RequestMethod;
import org.axe.exception.RestException;
import org.axe.util.JsonUtil;
import org.axe.util.LogUtil;

import com.tunnel.home.common.Constant;
import com.tunnel.home.dao.PayLogDao;
import com.tunnel.home.entity.PayLog;
import com.tunnel.home.entity.User;
import com.tunnel.home.server.PayService;

@Controller(basePath="/pay",desc="支付")
public class PayRest {
	
	@Autowired
	private PayService payService;
	@Autowired
	private PayLogDao payLogDao;
	
	@Request(path="/check_last",method=RequestMethod.GET,desc="检查最后一次支付是否成功")
	public String check_last(User user){
		PayLog lastPayLog = payLogDao.getLastPayLog(user.getId());
		if(lastPayLog == null){
			return "";
		}
		if(lastPayLog.getStatus() == 0){
			//计算剩余支付时间
			long time = lastPayLog.getExpireTime().getTime();
			long limitTime = time-System.currentTimeMillis();
			long hour = limitTime/3600000;
			limitTime = limitTime-hour*3600000;
			long min = limitTime/60000;
			limitTime = limitTime-min*60000;
			long sec = limitTime/1000;
			
			return "待支付，剩余时间："+hour+"小时"+min+"分"+sec+"秒";
		}
		if(lastPayLog.getStatus() == 1){
			return "支付成功";
		}
		if(lastPayLog.getStatus() == -1){
			return "已过期";
		}
		return "";
	}
	
	@Request(path="/create_wx_order",method=RequestMethod.POST,desc="创建支付订单")
	public String create_wx_order(
			@RequestParam(name="goods",required=true,desc="商品")String goods,
			User user){
		if(!Constant.GOODS_MAP.containsKey(goods)){
			throw new RestException("请重新选择");
		}
		
		String fee = Constant.GOODS_MAP.get(goods);
		try {
			return payService.createWxScanCodePayOrder(user.getId(), fee, goods);
		} catch (Exception e) {
			throw new RestException("订单创建失败："+e.getMessage());
		}
	}
	
	@FilterFuckOff
	@Request(path="/notify",method=RequestMethod.POST,desc="支付订单回调")
	public String pay_notify(Param param){
		try {
			payService.payNotify(param.getBodyParamMap());
			return "SUCCESS";
		} catch (Exception e) {
			LogUtil.log("notify报文："+JsonUtil.toJson(param.getBodyParamMap()));
			LogUtil.error(e);
		}
		return "";
	}
	
}
